#include "usart3.h"
#include "Sys_Config.h"
#if MD_USD_SALVE
#include "MDS_RTU_Serial_1.h"
#else 
#include "MDM_RTU_Serial.h"
#include "MD_RTU_SysInterface.h"
#include "MDM_RTU_Fun.h"
#endif

void RS485RWConvInit(void)
{
	GPIO_InitTypeDef gpio_structure;
	
	gpio_structure.GPIO_Mode=GPIO_Mode_OUT;
	gpio_structure.GPIO_OType=GPIO_OType_PP;
	gpio_structure.GPIO_Pin=GPIO_Pin_8;
	gpio_structure.GPIO_PuPd=GPIO_PuPd_NOPULL;
	gpio_structure.GPIO_Speed=GPIO_Fast_Speed;
	
	GPIO_Init(GPIOG,&gpio_structure); 
	
	RS485_RW_CONV=0;
}


void init_usart3(u32 baudRate)
{
	
	USART_InitTypeDef usart_structure;
	GPIO_InitTypeDef gpio_structure;
	NVIC_InitTypeDef nvic_structure;
	
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOG,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOG,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6,ENABLE);
	
	gpio_structure.GPIO_Mode=GPIO_Mode_AF;
	gpio_structure.GPIO_OType=GPIO_OType_PP;
	gpio_structure.GPIO_Pin=GPIO_Pin_9|GPIO_Pin_14;
	gpio_structure.GPIO_PuPd=GPIO_PuPd_UP;
	gpio_structure.GPIO_Speed=GPIO_Fast_Speed;
	
	GPIO_Init(GPIOG,&gpio_structure);
	
	GPIO_PinAFConfig(GPIOG,GPIO_PinSource9,GPIO_AF_USART6);
	GPIO_PinAFConfig(GPIOG,GPIO_PinSource14,GPIO_AF_USART6);
	
	gpio_structure.GPIO_Mode=GPIO_Mode_OUT;
	gpio_structure.GPIO_OType=GPIO_OType_PP;
	gpio_structure.GPIO_Pin=GPIO_Pin_8;
	gpio_structure.GPIO_PuPd=GPIO_PuPd_NOPULL;
	gpio_structure.GPIO_Speed=GPIO_Fast_Speed;
	
	GPIO_Init(GPIOG,&gpio_structure);
	
	usart_structure.USART_BaudRate=baudRate;
	usart_structure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
	usart_structure.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;
	usart_structure.USART_Parity=USART_Parity_No;
	usart_structure.USART_StopBits=USART_StopBits_1;
	usart_structure.USART_WordLength=USART_WordLength_8b;
	
	USART_Init(USART6,&usart_structure);
	
	USART_ITConfig(USART6,USART_IT_RXNE,ENABLE);
	
	nvic_structure.NVIC_IRQChannel=USART6_IRQn;
	nvic_structure.NVIC_IRQChannelCmd=ENABLE;
	nvic_structure.NVIC_IRQChannelPreemptionPriority=1;
	nvic_structure.NVIC_IRQChannelSubPriority=0;
	
	NVIC_Init(&nvic_structure);
	
	USART_Cmd(USART6,ENABLE);

	
	RS485RWConvInit();
}



void usart3_send_byte(u8 byte)
{
	while(USART_GetFlagStatus(USART6,USART_FLAG_TC)==RESET);	
	USART_SendData(USART6,byte);
	while(USART_GetFlagStatus(USART6,USART_FLAG_TC)==RESET);	
}
void usart3_send_bytes(u8 *bytes,int len)
{
	int i;
	for(i=0;i<len;i++)
	{
		usart3_send_byte(bytes[i]);
	}
}
void usart3_send_string(char *string)
{
	while(*string)
	{
		usart3_send_byte(*string++);
	}
}

void USART6_IRQHandler(void)
{
    if (USART_GetITStatus(USART6,USART_IT_RXNE) != RESET)
	{
			uint8_t data = USART_ReceiveData(USART6);
			#if !MD_RTU_USED_OS
				#if MD_USD_SALVE
					MDSSerialRecvByte_1(data);
				#else 
					#if MDM_USD_USART3
						MDMSerialRecvByte(data);
					#endif
				#endif
			#else
				extern Modbus_RTU modbus_RTU;
				MD_RTU_MsgPut((PModbusBase)(&modbus_RTU), MD_RTU_MSG_HANDLE_ARG(&modbus_RTU),(void*)(data),0);
			#endif
    }
}

